<template>
  <view class="wh_750 flex flex-column align-center bg_F5F5F5 pageHeight">
    <s-header-title ref="headerTitle" isDisplayBack
                    :title="page.options.flag == 1 ? `编辑${page.options.username}的生日`:'添加家庭成员生日'"
                    is-fixed background="#FFFFFF"
                    @getPageHeight="getPageHeight"></s-header-title>
    <view :style="{height:`${page.headerHeight}px`}"></view>
    <view class="birthday_date flex align-center justify-center mt_25" @click.stop="openBetterCalendar"
          v-if="!!form.dateBirth">
      <text class="birthday_date_text" :style="{
        color:date.type == 'lunar' ? '#9F9F9F' : '#000000'
      }">
        {{ solarCalendarDate }}
      </text>
      <text class="birthday_date_text ml_10" :style="{
        color:date.type == 'lunar' ? '#000000' : '#9F9F9F'
      }">
        {{ lunarCalendarDate }}
      </text>
    </view>
    <view class="birthday_date flex align-center justify-center mt_25" @click.stop="openBetterCalendar" v-else>
      点击设置日期
    </view>
    <view class="birthday_date flex align-center justify-center mt_25" @click.stop="goSelectFamilyMember">
      <text class="birthday_date_text">{{ !!form.selectName ? form.selectName : '点击选择家庭成员' }}</text>
    </view>
    <view class="birthday_tips flex flex-column">
      <text class="birthday_tips_text mt_9">提示：</text>
      <text class="birthday_tips_text mt_9">1.首页只能为家庭成员添加生日或纪念日</text>
      <text class="birthday_tips_text mt_9">2.非家庭成员如需要添加生日请在我的里面进行添加</text>
    </view>
    <view class="birthday_bottomButton flex align-center justify-center mt_239"
          @click.stop="debounce(submit,1500,true)">
      <text class="birthday_bottomButton_text">完成</text>
    </view>

    <s-better-calendar class="z-999"
                       ref="betterCalendarRef"
                       :maxYear="new Date().getFullYear()"
                       :default-type="date.type"
                       :default-value="date.defaultValue"
                       :showCalendar="page.showCalendar"
                       :isLeap="date.isLeap"
                       @confirm="selectDate"
                       @cancel="page.showCalendar = false"
    ></s-better-calendar>
  </view>
</template>

<script setup>
  import HeaderTitle from '@/pages/family/components/headerTitle.vue';
  import { computed, reactive, ref } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import dayjs from 'dayjs';
  import { calendar } from '@/sheep/components/s-better-calendar/calendar';
  import SBetterCalendar from '@/sheep/components/s-better-calendar/s-better-calendar.vue';
  import sheep from '@/sheep';
  import debounce from '@/sheep/helper/debounce';

  const page = reactive({
    headerHeight: 0,
    options: {},
    showCalendar: false,
  });
  const form = reactive({
    selectId: '',
    selectName: '',
  });

  const INIT_DAY_TYPE = 'solar';
  const INIT_DAY_TIMESTAMP = dayjs().valueOf();
  const INIT_DAY = dayjs().format('YYYY-MM-DD');
  const date = reactive({
    type: INIT_DAY_TYPE, // 类型
    timestamp: INIT_DAY_TIMESTAMP, // 时间戳
    solarDate: INIT_DAY, // 公历日期 - 文本（2000-1-1）
    lunarDate: '', // 农历日期 - 文本（己卯年冬月廿五(2000-1-1)）
    lunarDateNumber: '', // 农历生日的数字写法（1999-12-25）
    defaultValue: [100, 0, 0], // 默认选中的日期
  });
  // 阳历日期
  const solarCalendarDate = computed(() => {
    if (!!form.dateBirth) {
      if (date.type == 'lunar') {
        let dt = calendar.lunar2solar(form.dateBirth.split('-')[0], form.dateBirth.split('-')[1], form.dateBirth.split('-')[2], !!date.isLeap ? true : false);
        return dayjs(dt.date).format('YYYY年MM月DD日');
      } else {
        return dayjs(form.dateBirth).format('YYYY年MM月DD日');
      }
    } else {
      return '';
    }
  });
  // 阴历日期
  const lunarCalendarDate = computed(() => {
    if (!!form.dateBirth) {
      if (date.type == 'lunar') {
        let dt = calendar.lunar2solar(form.dateBirth.split('-')[0], form.dateBirth.split('-')[1], form.dateBirth.split('-')[2], !!date.isLeap ? true : false);
        return `${dt.gzYear}年 ${calendar.toChinaYear(dt.lYear)}${dt.IMonthCn}${dt.IDayCn}`;
      } else {
        let dt = calendar.solar2lunar(form.dateBirth.split('-')[0], form.dateBirth.split('-')[1], form.dateBirth.split('-')[2]);
        return `${dt.gzYear}年 ${calendar.toChinaYear(dt.lYear)}${dt.IMonthCn}${dt.IDayCn}`;
      }
    } else {
      return '';
    }
  });

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  onLoad((options) => {
    page.options = options;
    if (options.flag == 1) {
      form.selectId = options.member_id;
      form.dateBirth = options.date;
      form.selectName = options.username;
      date.solarDate = options.date;
      date.type = options.time_type != 1 ? 'solar' : 'lunar';
      date.timestamp = dayjs(options.date).valueOf();
      date.defaultValue = options.date != '' ? [options.date.split('-')[0] - 1900, options.date.split('-')[1] - 1, options.date.split('-')[2] - 1] : [100, 0, 0];
      date.isLeap = options.isLeapMonth == 2 ? true : false;
    } else {
      date.defaultValue = [100, 0, 0];
    }
    uni.$on('selectMember', info => {
      form.selectId = info.id;
      form.selectName = info.nickname || info.remark;
    });
  });
  const betterCalendarRef = ref();

  function openBetterCalendar() {
    if (!!form.dateBirth) {
      if (date.type == 'lunar') {
        let day = calendar.leapMonth(Number(date.defaultValue[0]) + 1900);
        if (!!date.isLeap) {
          let arr = [date.defaultValue[0], date.defaultValue[1] + 1, date.defaultValue[2]];
          betterCalendarRef.value.setPicker(arr, date.type, date.isLeap);
        } else {
          if (day <= 0) {
            betterCalendarRef.value.setPicker(date.defaultValue, date.type, date.isLeap);
          } else {
            if (form.dateBirth.split('-')[1] > day) {
              let arr = [date.defaultValue[0], date.defaultValue[1] + 1, date.defaultValue[2]];
              betterCalendarRef.value.setPicker(arr, date.type, date.isLeap);
            } else {
              if (date.isLeap) {
                let arr = [date.defaultValue[0], date.defaultValue[1] + 1, date.defaultValue[2]];
                betterCalendarRef.value.setPicker(arr, date.type, date.isLeap);
              } else {
                betterCalendarRef.value.setPicker(date.defaultValue, date.type, date.isLeap);
              }
            }

          }
        }
      } else {
        let arr = [];
        arr[0] = Number(form.dateBirth.split('-')[0] - 1900);
        arr[1] = Number(form.dateBirth.split('-')[1]) - 1;
        arr[2] = Number(form.dateBirth.split('-')[2]) - 1;
        console.log(arr);
        betterCalendarRef.value.setPicker(arr, date.type, false);
      }
    }
    page.showCalendar = true;
  }

  function selectDate(e) {
    // console.log(e);
    date.type = e.type;
    date.timestamp = dayjs(e.solarDate).valueOf();
    date.solarDate = e.solarDate;
    date.lunarDate = e.lunarDate;
    date.lunarDateNumber = e.lunarDateNumber;
    date.isLeap = e.isLeap; // 一年里是否有闰月
    form.dateBirth = e.type == 'lunar' ? e.lunarDateNumber : e.solarDate;
    // this.date.type = e.type == 'lunar' ? 1 : 2
    page.showCalendar = false;
    date.defaultValue = e.selectValue;
  }

  function goSelectFamilyMember() {
    if (page.options.flag == 1) {
      return;
    }
    sheep.$router.go('/pages/family/selectFamilyMember', {
      family_id: page.options.family_id,
    });
  }

  async function submit() {
    if (form.selectId == '') {
      sheep.$helper.toast('请选择家庭成员');
      return;
    }
    if (form.dateBirth == '') {
      sheep.$helper.toast('请选择日期');
      return;
    }
    if (page.options.is_genealoy == 1) {
      const { code, msg } = await sheep.$api.genealogy.updateMemberInfo({
        id: form.selectId,
        isLeapMonth: !date.isLeap ? 1 : 2,
        birthday: date.type == 'solar' ? date.solarDate : date.lunarDateNumber,
        birthday_type: date.type == 'solar' ? 2 : 1,
      });
      if (code == 1) {
        console.log(1322);
        sheep.$helper.toast('设置成功');
        setTimeout(() => {
          uni.$emit('refreshFamilyMemoryDay');
          uni.navigateBack();
        }, 500);
      } else {
        sheep.$helper.toast(msg);
      }
    } else {
      const { code, msg } = await sheep.$api.family.updateFamilyMemberInfo({
        family_id: page.options.family_id,
        member_id: form.selectId,
        is_leap_month: !date.isLeap ? 1 : 2,
        date: date.type == 'solar' ? date.solarDate : date.lunarDateNumber,
        time_type: date.type == 'solar' ? 2 : 1,
      });
      if (code == 1) {
        sheep.$helper.toast('设置成功');
        setTimeout(() => {
          uni.$emit('refreshFamilyMemoryDay');
          uni.navigateBack();
        }, 500);
      } else {
        sheep.$helper.toast(msg);
      }
    }
  }
</script>


<style scoped lang="scss">
  .birthday_date {
    width: 702rpx;
    height: 80rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 40rpx 40rpx;

    .birthday_date_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #9F9F9F;
    }
  }

  .birthday_tips {
    width: 702rpx;

    .birthday_tips_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #9F9F9F;
    }
  }

  .birthday_bottomButton {
    width: 362rpx;
    height: 80rpx;
    background: #FF4206;
    border-radius: 41rpx 41rpx 41rpx 41rpx;

    .birthday_bottomButton_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #FFFFFF;
    }
  }
</style>
